﻿/*
 * @author: wizardc
 */

using System;
using System.Collections.Generic;

namespace Dou.Utils
{
    /// <summary>
    /// 可回收对象管理类
    /// </summary>
    public static class Recyclable
    {
        private static Dictionary<Type, ObjectPool> _map = new Dictionary<Type, ObjectPool>();

        public static void Register<T>(Func<object> creator)
        {
            _map.Add(typeof(T), new ObjectPool(50, creator));
        }

        public static void Register<T>(int maxCount, Func<object> creator)
        {
            _map.Add(typeof(T), new ObjectPool(maxCount, creator));
        }

        public static ObjectPool GetPool<T>()
        {
            Type type = typeof(T);
            if (!_map.ContainsKey(type))
            {
                return null;
            }
            return _map[type];
        }

        public static T Get<T>()
        {
            Type type = typeof(T);
            if (!_map.ContainsKey(type))
            {
                throw new Exception("类型\"" + type + "\"没有初始化");
            }
            ObjectPool pool = _map[type];
            return (T) pool.Take();
        }

        public static void Recycle<T>(object obj)
        {
            Type type = typeof(T);
            if (_map.ContainsKey(type))
            {
                ObjectPool pool = _map[type];
                pool.Join(obj);
            }
        }

        public static void Recycle(object obj)
        {
            Type type = obj.GetType();
            if (_map.ContainsKey(type))
            {
                ObjectPool pool = _map[type];
                pool.Join(obj);
            }
        }
    }
}
